package org.programmers.anonymous.fightrobots.utils;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.programmers.anonymous.fightrobots.model.IMessage;
import org.programmers.anonymous.fightrobots.model.IURLId;
import org.programmers.anonymous.fightrobots.model.Message;
import org.programmers.anonymous.fightrobots.model.MessageSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class RESTClient {
	
	private static final Logger logger = LoggerFactory.getLogger(RESTClient.class);
	
	public IMessage executeRequest(IMessage requestMsg)
	{
		IURLId addressURL = null;
		IMessage responseMsg = null;
		
		addressURL = requestMsg.getMyReceiver();
		
		ClientConfig config = new DefaultClientConfig();
		config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
		Client client = Client.create(config);
		 
		URI theUri = UriBuilder.fromUri(addressURL.getURL()).build();
		 
		WebResource service = client.resource(theUri);
		
		String theJSONMessage = new MessageSerializer().serialize((Message)requestMsg);
		
		logger.debug(" executeRequest, JSON_MSG: >>>  "  + theJSONMessage);
		
		ClientResponse  response = service
									.path("fight-service").path("message")
									.type(MediaType.APPLICATION_JSON_TYPE)
									.accept(MediaType.APPLICATION_JSON_TYPE)
									.post(ClientResponse.class,theJSONMessage);
			
		logger.debug(" executeRequest, STATUS: <<< " + response.getStatus());
		
		String jsonResponse = response.getEntity(String.class);
		
		logger.debug(" executeRequest, JSON_MSG: <<< "  + jsonResponse);
		
		responseMsg = new MessageSerializer().deserialize(jsonResponse);;
		
		logger.info("executeRequest, MSG <<< : " + responseMsg);
		
		if (response.getStatus() != 200) {
			logger.error("Failed : HTTP error code : "
			     + response.getStatus());
			return null;
		}else{
			return responseMsg;
		}
	}

}
